<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="kmeans," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="机器学习之kmeans算法今天我们开始介绍一个无监督机器学习算法。那么什么是有监督？什么又是无监督呢？ 有监督：有标签值说明每个样本是属于什么结果的算法 无监督：没有标签说明每个样本所属的算法 监督算法 kmeans今天的算法是一个聚类算法，用于将相似的东西分到一组。对于这类算法，其难点是分好类后我们并不知道这个模型的好坏，不好评估 无监督的聚类算法比较多，这一篇文章讲 kmeans 基本概念 k">
<meta name="keywords" content="kmeans">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习之kmeans算法">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/11/29/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="机器学习之kmeans算法今天我们开始介绍一个无监督机器学习算法。那么什么是有监督？什么又是无监督呢？ 有监督：有标签值说明每个样本是属于什么结果的算法 无监督：没有标签说明每个样本所属的算法 监督算法 kmeans今天的算法是一个聚类算法，用于将相似的东西分到一组。对于这类算法，其难点是分好类后我们并不知道这个模型的好坏，不好评估 无监督的聚类算法比较多，这一篇文章讲 kmeans 基本概念 k">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/11/29/1/1.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/11/29/1/2.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/11/29/1/3.png">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习之kmeans算法">
<meta name="twitter:description" content="机器学习之kmeans算法今天我们开始介绍一个无监督机器学习算法。那么什么是有监督？什么又是无监督呢？ 有监督：有标签值说明每个样本是属于什么结果的算法 无监督：没有标签说明每个样本所属的算法 监督算法 kmeans今天的算法是一个聚类算法，用于将相似的东西分到一组。对于这类算法，其难点是分好类后我们并不知道这个模型的好坏，不好评估 无监督的聚类算法比较多，这一篇文章讲 kmeans 基本概念 k">
<meta name="twitter:image" content="https://wangxiaochuang.github.io/blog/2018/11/29/1/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/11/29/1.html"/>





  <title>机器学习之kmeans算法 | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/11/29/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">机器学习之kmeans算法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-29T22:40:49+00:00">
                2018-11-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/kmeans/" itemprop="url" rel="index">
                    <span itemprop="name">kmeans</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/11/29/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/11/29/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/11/29/1.html" class="leancloud_visitors" data-flag-title="机器学习之kmeans算法">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="机器学习之kmeans算法"><a href="#机器学习之kmeans算法" class="headerlink" title="机器学习之kmeans算法"></a>机器学习之kmeans算法</h1><p>今天我们开始介绍一个无监督机器学习算法。那么什么是有监督？什么又是无监督呢？</p>
<p>有监督：有标签值说明每个样本是属于什么结果的算法</p>
<p>无监督：没有标签说明每个样本所属的算法</p>
<h2 id="监督算法-kmeans"><a href="#监督算法-kmeans" class="headerlink" title="监督算法 kmeans"></a>监督算法 kmeans</h2><p>今天的算法是一个聚类算法，用于将相似的东西分到一组。对于这类算法，其难点是分好类后我们并不知道这个模型的好坏，不好评估</p>
<p>无监督的聚类算法比较多，这一篇文章讲 <code>kmeans</code></p>
<h3 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h3><ol>
<li>k值<br> 要得到的簇的个数即为k值</li>
<li>质心<br> 均值，即向量各维取平均即可</li>
<li>距离的度量<br> 常用欧几里得距离和余弦相似度（需要先标准化）</li>
<li>优化目标 $min\sum_{i=1}^{K} \sum_{x \in C_i} dist(C_i, x)^2$<br> i=1到K，表示我们要优化的每个簇。我们的目标是让每个簇的每个点到中心的距离越小越好</li>
</ol>
<h3 id="kmeans处理流程"><a href="#kmeans处理流程" class="headerlink" title="kmeans处理流程"></a>kmeans处理流程</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1. 假设k为2，我们就初始化随机选择两个点（初始质心）</span><br><span class="line">2. 遍历所有样本点，计算每个点到这两个质新的距离，并且将距离小的归到对应的类别</span><br><span class="line">3. 遍历完成后肯定就分层了两个类别了，这个时候我们要开始迭代了</span><br><span class="line">4. 分别计算这两个类别的质心（第一次是随机选择的）</span><br><span class="line">5. 重新遍历每个点进行重分类</span><br><span class="line">6. 多次迭代后，质心应该就是一个稳定值了，聚类就完成</span><br></pre></td></tr></table></figure>
<h3 id="优缺点"><a href="#优缺点" class="headerlink" title="优缺点"></a>优缺点</h3><p><strong>优点</strong></p>
<p>简单、快速、适合常规数据集</p>
<p><strong>缺点</strong></p>
<ol>
<li>K值难以确定</li>
<li>复杂度与样本数呈线性关系</li>
<li>另外一个问题就是很难发现任意形状的簇（比如两个环绕的簇，这样kmeans就发现不了）</li>
<li>受<em>初始值</em>的影响非常大</li>
</ol>
<h3 id="可视化展示"><a href="#可视化展示" class="headerlink" title="可视化展示"></a>可视化展示</h3><p><a href="https://www.naftaliharris.com/blog/visualizing-k-means-clustering/">Visualizing K-Means Clustering</a> 是一个国外的网友做的一个可视化网站</p>
<p>尝试一下不同类型的数据集下，kmeans的效果</p>
<h2 id="使用sklearn进行kmeans聚类"><a href="#使用sklearn进行kmeans聚类" class="headerlink" title="使用sklearn进行kmeans聚类"></a>使用sklearn进行kmeans聚类</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer = pd.read_csv(<span class="string">'data.txt'</span>, sep=<span class="string">' '</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>X = beer[[<span class="string">"calories"</span>, <span class="string">"sodium"</span>, <span class="string">"alcohol"</span>, <span class="string">"cost"</span>]]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> sklearn.cluster <span class="keyword">import</span> KMeans</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>km = KMeans(n_clusters=<span class="number">3</span>).fit(X)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>km2 = KMeans(n_clusters=<span class="number">2</span>).fit(X)</span><br><span class="line"><span class="comment"># 查看每个样本分类后的类别，从0开始计数</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>km.labels_</span><br><span class="line">array([<span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">0</span>],</span><br><span class="line">      dtype=int32)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>km2.labels_</span><br><span class="line">array([<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>],</span><br><span class="line">      dtype=int32)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer[<span class="string">'cluster'</span>] = km.labels_</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer[<span class="string">'cluster2'</span>] = km2.labels_</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer.sort_values(<span class="string">'cluster'</span>)</span><br><span class="line">                    name  calories  sodium  alcohol  cost  cluster  cluster2</span><br><span class="line"><span class="number">9</span>        Budweiser_Light       <span class="number">113</span>       <span class="number">8</span>      <span class="number">3.7</span>  <span class="number">0.40</span>        <span class="number">0</span>         <span class="number">1</span></span><br><span class="line"><span class="number">11</span>           Coors_Light       <span class="number">102</span>      <span class="number">15</span>      <span class="number">4.1</span>  <span class="number">0.46</span>        <span class="number">0</span>         <span class="number">1</span></span><br><span class="line"><span class="number">8</span>            Miller_Lite        <span class="number">99</span>      <span class="number">10</span>      <span class="number">4.3</span>  <span class="number">0.43</span>        <span class="number">0</span>         <span class="number">1</span></span><br><span class="line"><span class="number">19</span>         Schlitz_Light        <span class="number">97</span>       <span class="number">7</span>      <span class="number">4.2</span>  <span class="number">0.47</span>        <span class="number">0</span>         <span class="number">1</span></span><br><span class="line"><span class="number">4</span>               Heineken       <span class="number">152</span>      <span class="number">11</span>      <span class="number">5.0</span>  <span class="number">0.77</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">5</span>          Old_Milwaukee       <span class="number">145</span>      <span class="number">23</span>      <span class="number">4.6</span>  <span class="number">0.28</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">6</span>             Augsberger       <span class="number">175</span>      <span class="number">24</span>      <span class="number">5.5</span>  <span class="number">0.40</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">7</span>   Srohs_Bohemian_Style       <span class="number">149</span>      <span class="number">27</span>      <span class="number">4.7</span>  <span class="number">0.42</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">2</span>              Lowenbrau       <span class="number">157</span>      <span class="number">15</span>      <span class="number">0.9</span>  <span class="number">0.48</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">10</span>                 Coors       <span class="number">140</span>      <span class="number">18</span>      <span class="number">4.6</span>  <span class="number">0.44</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">1</span>                Schlitz       <span class="number">151</span>      <span class="number">19</span>      <span class="number">4.9</span>  <span class="number">0.43</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">12</span>        Michelob_Light       <span class="number">135</span>      <span class="number">11</span>      <span class="number">4.2</span>  <span class="number">0.50</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">13</span>                 Becks       <span class="number">150</span>      <span class="number">19</span>      <span class="number">4.7</span>  <span class="number">0.76</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">14</span>                 Kirin       <span class="number">149</span>       <span class="number">6</span>      <span class="number">5.0</span>  <span class="number">0.79</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">16</span>                 Hamms       <span class="number">139</span>      <span class="number">19</span>      <span class="number">4.4</span>  <span class="number">0.43</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">17</span>   Heilemans_Old_Style       <span class="number">144</span>      <span class="number">24</span>      <span class="number">4.9</span>  <span class="number">0.43</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">3</span>            Kronenbourg       <span class="number">170</span>       <span class="number">7</span>      <span class="number">5.2</span>  <span class="number">0.73</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">0</span>              Budweiser       <span class="number">144</span>      <span class="number">15</span>      <span class="number">4.7</span>  <span class="number">0.43</span>        <span class="number">1</span>         <span class="number">0</span></span><br><span class="line"><span class="number">18</span>   Olympia_Goled_Light        <span class="number">72</span>       <span class="number">6</span>      <span class="number">2.9</span>  <span class="number">0.46</span>        <span class="number">2</span>         <span class="number">1</span></span><br><span class="line"><span class="number">15</span>     Pabst_Extra_Light        <span class="number">68</span>      <span class="number">15</span>      <span class="number">2.3</span>  <span class="number">0.38</span>        <span class="number">2</span>         <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cluster_centers = km.cluster_centers_</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cluster_centers_2 = km2.cluster_centers_</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer.groupby(<span class="string">"cluster"</span>).mean()</span><br><span class="line">         calories  sodium   alcohol      cost  cluster2</span><br><span class="line">cluster</span><br><span class="line"><span class="number">0</span>          <span class="number">102.75</span>    <span class="number">10.0</span>  <span class="number">4.075000</span>  <span class="number">0.440000</span>         <span class="number">1</span></span><br><span class="line"><span class="number">1</span>          <span class="number">150.00</span>    <span class="number">17.0</span>  <span class="number">4.521429</span>  <span class="number">0.520714</span>         <span class="number">0</span></span><br><span class="line"><span class="number">2</span>           <span class="number">70.00</span>    <span class="number">10.5</span>  <span class="number">2.600000</span>  <span class="number">0.420000</span>         <span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>beer.groupby(<span class="string">"cluster2"</span>).mean()</span><br><span class="line">            calories     sodium   alcohol      cost   cluster</span><br><span class="line">cluster2</span><br><span class="line"><span class="number">0</span>         <span class="number">150.000000</span>  <span class="number">17.000000</span>  <span class="number">4.521429</span>  <span class="number">0.520714</span>  <span class="number">1.000000</span></span><br><span class="line"><span class="number">1</span>          <span class="number">91.833333</span>  <span class="number">10.166667</span>  <span class="number">3.583333</span>  <span class="number">0.433333</span>  <span class="number">0.666667</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 可视化展示</span></span><br><span class="line"><span class="comment"># 获取中心点，就是均值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>centers = beer.groupby(<span class="string">"cluster"</span>).mean().reset_index()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.rcParams[<span class="string">'font.size'</span>] = <span class="number">14</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>colors = np.array([<span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>, <span class="string">'yellow'</span>])</span><br><span class="line"><span class="comment"># 不同类别的点画不同的颜色</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.scatter(beer[<span class="string">"calories"</span>], beer[<span class="string">"alcohol"</span>], c=colors[beer[<span class="string">"cluster"</span>]])</span><br><span class="line">&lt;matplotlib.collections.PathCollection object at <span class="number">0x1a1a580f98</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.scatter(centers.calories, centers.alcohol, linewidths=<span class="number">3</span>, marker=<span class="string">'+'</span>, s=<span class="number">300</span>, c=<span class="string">'black'</span>)</span><br><span class="line">&lt;matplotlib.collections.PathCollection object at <span class="number">0x1a1a9f43c8</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlabel(<span class="string">"Calories"</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">0</span>,<span class="string">'Calories'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylabel(<span class="string">"Alcohol"</span>)</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">0.5</span>,<span class="string">'Alcohol'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
<img src="/blog/2018/11/29/1/1.png" title="分类结果">
<p>我们可以看看所有两两组合的结果，使用matrix<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> pandas.plotting <span class="keyword">import</span> scatter_matrix</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>scatter_matrix(beer[[<span class="string">"calories"</span>, <span class="string">"sodium"</span>, <span class="string">"alcohol"</span>, <span class="string">"cost"</span>]], s=<span class="number">100</span>, alpha=<span class="number">1</span>, c=colors[beer[<span class="string">"cluster</span></span><br><span class="line"><span class="string">"</span>]], figsize=(<span class="number">10</span>, <span class="number">8</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.suptitle(<span class="string">"With 3 centroids initialized"</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">0.98</span>,<span class="string">'With 3 centroids initialized'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure></p>
<img src="/blog/2018/11/29/1/2.png" title="matrix">
<p>我们对数据进行归一化后看结果<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> StandardScaler</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>scaler = StandardScaler()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>X_scaled = scaler.fit_transform(X)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>X_scaled</span><br><span class="line">array([[ <span class="number">0.38791334</span>,  <span class="number">0.00779468</span>,  <span class="number">0.43380786</span>, <span class="number">-0.45682969</span>],       </span><br><span class="line">       [ <span class="number">0.6250656</span> ,  <span class="number">0.63136906</span>,  <span class="number">0.62241997</span>, <span class="number">-0.45682969</span>],</span><br><span class="line">       [ <span class="number">0.82833896</span>,  <span class="number">0.00779468</span>, <span class="number">-3.14982226</span>, <span class="number">-0.10269815</span>],</span><br><span class="line">       [ <span class="number">1.26876459</span>, <span class="number">-1.23935408</span>,  <span class="number">0.90533814</span>,  <span class="number">1.66795955</span>],</span><br><span class="line">       [ <span class="number">0.65894449</span>, <span class="number">-0.6157797</span> ,  <span class="number">0.71672602</span>,  <span class="number">1.95126478</span>],</span><br><span class="line">       [ <span class="number">0.42179223</span>,  <span class="number">1.25494344</span>,  <span class="number">0.3395018</span> , <span class="number">-1.5192243</span> ],</span><br><span class="line">       [ <span class="number">1.43815906</span>,  <span class="number">1.41083704</span>,  <span class="number">1.1882563</span> , <span class="number">-0.66930861</span>],</span><br><span class="line">       [ <span class="number">0.55730781</span>,  <span class="number">1.87851782</span>,  <span class="number">0.43380786</span>, <span class="number">-0.52765599</span>],</span><br><span class="line">       [<span class="number">-1.1366369</span> , <span class="number">-0.7716733</span> ,  <span class="number">0.05658363</span>, <span class="number">-0.45682969</span>],</span><br><span class="line">       [<span class="number">-0.66233238</span>, <span class="number">-1.08346049</span>, <span class="number">-0.5092527</span> , <span class="number">-0.66930861</span>],</span><br><span class="line">       [ <span class="number">0.25239776</span>,  <span class="number">0.47547547</span>,  <span class="number">0.3395018</span> , <span class="number">-0.38600338</span>],</span><br><span class="line">       [<span class="number">-1.03500022</span>,  <span class="number">0.00779468</span>, <span class="number">-0.13202848</span>, <span class="number">-0.24435076</span>],</span><br><span class="line">       [ <span class="number">0.08300329</span>, <span class="number">-0.6157797</span> , <span class="number">-0.03772242</span>,  <span class="number">0.03895447</span>],</span><br><span class="line">       [ <span class="number">0.59118671</span>,  <span class="number">0.63136906</span>,  <span class="number">0.43380786</span>,  <span class="number">1.88043848</span>],</span><br><span class="line">       [ <span class="number">0.55730781</span>, <span class="number">-1.39524768</span>,  <span class="number">0.71672602</span>,  <span class="number">2.0929174</span> ],</span><br><span class="line">       [<span class="number">-2.18688263</span>,  <span class="number">0.00779468</span>, <span class="number">-1.82953748</span>, <span class="number">-0.81096123</span>],</span><br><span class="line">       [ <span class="number">0.21851887</span>,  <span class="number">0.63136906</span>,  <span class="number">0.15088969</span>, <span class="number">-0.45682969</span>],</span><br><span class="line">       [ <span class="number">0.38791334</span>,  <span class="number">1.41083704</span>,  <span class="number">0.62241997</span>, <span class="number">-0.45682969</span>],</span><br><span class="line">       [<span class="number">-2.05136705</span>, <span class="number">-1.39524768</span>, <span class="number">-1.26370115</span>, <span class="number">-0.24435076</span>],</span><br><span class="line">       [<span class="number">-1.20439469</span>, <span class="number">-1.23935408</span>, <span class="number">-0.03772242</span>, <span class="number">-0.17352445</span>]])</span><br><span class="line"><span class="comment"># 后面的操作跟以上的一样，请自行操作一下吧</span></span><br></pre></td></tr></table></figure></p>
<p><strong>关于归一化的效果</strong></p>
<p>一般情况下都会将数据进行归一化以消除数值大小对重要性的影响，但是也未必归一化后的结果就比原始数据好，因为可能某些数据的重要程度就是很小，归一化后反而将重要性提高了</p>
<h2 id="模型效果评估"><a href="#模型效果评估" class="headerlink" title="模型效果评估"></a>模型效果评估</h2><p>聚类评估：轮廓系数（Silhouette Coefficient）</p>
<script type="math/tex; mode=display">
s(i) = \frac{b(i) - a(i)}{max(a(i), b(i))}</script><script type="math/tex; mode=display">\left.
\begin{array}{1}
1-\frac{a(i)}{b(i)} \text{,}& a(i) < b(i)\\
1-\frac{a(i)}{b(i)} \text{,}& a(i) = b(i)\\
1-\frac{a(i)}{b(i)} \text{,}& a(i) > b(i)\\
\end{array}
\right\}=f(n)</script><ul>
<li>计算样本i到同族其他样本的平均距离ai。ai越小说明样本i越应该被聚类到该簇，将ai称为样本i的簇内不相似度</li>
<li>计算样本i到其他同簇Cj的所有样本的平均距离bij，称为样本i与簇Cj的不相似度。定义样本i的簇间不相似度：$b_{i} = min(b_{i1}, b_{i2}, …, b_{ik})$</li>
<li>si接近1，说明样本i簇类合理</li>
<li>si接近-1，说明样本i更应该分类到另外的簇</li>
<li>若si接近0，说明样本i在两个簇的边界上</li>
</ul>
<p>以上面的例子算轮廓系数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> sklearn <span class="keyword">import</span> metrics</span><br><span class="line"><span class="comment"># 传入样本值与分类结果</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>score_scaled = metrics.silhouette_score(X, beer.cluster)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>score = metrics.silhouette_score(X, beer.cluster)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>score</span><br><span class="line"><span class="number">0.6731775046455796</span></span><br></pre></td></tr></table></figure>
<p>我们可能根据score值来选取合适的簇值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>scores = []</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> k <span class="keyword">in</span> range(<span class="number">2</span>, <span class="number">20</span>):</span><br><span class="line"><span class="meta">... </span>    labels = KMeans(n_clusters=k).fit(X).labels_</span><br><span class="line"><span class="meta">... </span>    score = metrics.silhouette_score(X, labels)</span><br><span class="line"><span class="meta">... </span>    scores.append(score)...</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>scores</span><br><span class="line">[<span class="number">0.6917656034079486</span>, <span class="number">0.6731775046455796</span>, <span class="number">0.5857040721127795</span>, <span class="number">0.422548733517202</span>, <span class="number">0.4559182167013377</span>, <span class="number">0.4377611669796312</span></span><br><span class="line"><span class="number">4</span>, <span class="number">0.38946337473125997</span>, <span class="number">0.39746405172426014</span>, <span class="number">0.3915697409245163</span>, <span class="number">0.3413109618039333</span>, <span class="number">0.3459775237127248</span>, <span class="number">0.31221439248</span></span><br><span class="line"><span class="number">428434</span>, <span class="number">0.30707782144770296</span>, <span class="number">0.31834561839139497</span>, <span class="number">0.2849514001174898</span>, <span class="number">0.23498077333071996</span>, <span class="number">0.1588091017496281</span>, <span class="number">0.08423</span></span><br><span class="line"><span class="number">051380151177</span>]</span><br><span class="line"><span class="comment"># 我们画图更直观看看结果</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(list(range(<span class="number">2</span>, <span class="number">20</span>)), scores)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1a1f153be0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlabel(<span class="string">"Number of Clusters Initialized"</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">0</span>,<span class="string">'Number of Clusters Initialized'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylabel(<span class="string">"Sibouette Score"</span>)</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">0.5</span>,<span class="string">'Sibouette Score'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
<img src="/blog/2018/11/29/1/3.png">
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/kmeans/" rel="tag"># kmeans</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/11/18/1.html" rel="next" title="计算机的负数表示详解">
                <i class="fa fa-chevron-left"></i> 计算机的负数表示详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/11/29/2.html" rel="prev" title="机器学习之DBSCAN算法">
                机器学习之DBSCAN算法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#机器学习之kmeans算法"><span class="nav-number">1.</span> <span class="nav-text">机器学习之kmeans算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#监督算法-kmeans"><span class="nav-number">1.1.</span> <span class="nav-text">监督算法 kmeans</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本概念"><span class="nav-number">1.1.1.</span> <span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#kmeans处理流程"><span class="nav-number">1.1.2.</span> <span class="nav-text">kmeans处理流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优缺点"><span class="nav-number">1.1.3.</span> <span class="nav-text">优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可视化展示"><span class="nav-number">1.1.4.</span> <span class="nav-text">可视化展示</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用sklearn进行kmeans聚类"><span class="nav-number">1.2.</span> <span class="nav-text">使用sklearn进行kmeans聚类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模型效果评估"><span class="nav-number">1.3.</span> <span class="nav-text">模型效果评估</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
